package autotest.web.framework.plugin.wizards;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.wizards.NewClassWizardPage;
import org.eclipse.jface.viewers.IStructuredSelection;

import autotest.web.framework.plugin.CodeGenerator;

public class NewPageWizardClassPage extends NewClassWizardPage
{
	private Map<String, String> pageFieldMap = new HashMap<String, String>();
	private CodeGenerator codeGenerator;
	
	@Override
	public void init(IStructuredSelection selection)
	{
		super.init(selection);
		
		setSuperClass("org.suren.autotest.web.framework.page.Page", false);
		setAddComments(true, false);
	}

	@Override
	protected void createTypeMembers(IType type, ImportsManager imports,
			IProgressMonitor monitor) throws CoreException
	{
		super.createTypeMembers(type, imports, monitor);
		
		codeGenerator = new CodeGenerator(type, imports);
		codeGenerator.addAnnotation(type, new StringBuffer("@Component "));
		
		Set<String> keySet = getPageFieldMap().keySet();
		Iterator<String> it = keySet.iterator();
		while(it.hasNext())
		{
			String name = it.next();
			String fieldType = getPageFieldMap().get(name);
			
			createFiled(name, fieldType);
			
			imports.addImport("org.suren.autotest.web.framework.core.ui." + fieldType);
			
			getGetterMethod(name, fieldType);
			
			getSetterMethod(name, fieldType);
		}
		
		imports.addImport("org.suren.autotest.web.framework.page.Page");
		imports.addImport("org.springframework.beans.factory.annotation.Autowired");
		imports.addImport("org.springframework.stereotype.Component");
	}
	
	private void createFiled(String name, String type)
	{
		try
		{
			IField field = codeGenerator.addField("private", type, name);
			
			StringBuffer buf = new StringBuffer();
			buf.append("@Autowired ");
			codeGenerator.addAnnotation(field, buf);
		}
		catch (JavaModelException e)
		{
			e.printStackTrace();
		}
	}
	
	private void getGetterMethod(String name, String type)
	{
		try
		{
			codeGenerator.addGetter(type, name);
		}
		catch (CoreException e)
		{
			e.printStackTrace();
		}
	}
	
	private void getSetterMethod(String name, String type)
	{
		try
		{
			codeGenerator.addSetter(type, name);
		}
		catch (CoreException e)
		{
			e.printStackTrace();
		}
	}

	public Map<String, String> getPageFieldMap()
	{
		return pageFieldMap;
	}

	public void setPageFieldMap(Map<String, String> pageFieldMap)
	{
		this.pageFieldMap = pageFieldMap;
	}
	
}